package com.winner.crmsoftware.customers;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.winner.crmsoftware.addcustomer.AddCustomerActivity;
import com.winner.crmsoftware.location.GPSTracker;
import com.winner.crmsoftware.main.R;
import com.winner.srmsoftware.json.ServiceHandler;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;

public class ListCustomerActivity extends Activity {

	private ProgressDialog pDialog;
	ArrayList<Customer> dataArrayList = new ArrayList<Customer>();
	private static String url = "http://103.28.37.16:8080/crm_software/get_all_customers.php";
	private static final String TAG_CUSTOMER = "customers";
	private static final String TAG_ID = "id";
	private static final String TAG_NAME = "last_name";
	private static final String TAG_ADDRESS = "address";
	private static final String TAG_EMAIL = "email";
	private static final String TAG_LATITUDE = "latitude";
	private static final String TAG_LONGTITUDE = "longtitude";
	private static final String TAG_PHONE_NUMBER = "phone_number";
	private static final String TAG_EMPLOYEE = "employee";
	public GPSTracker gps;
	JSONArray customerJsonArray = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.customer_list);

		gps = new GPSTracker(ListCustomerActivity.this);
		
		if (!gps.canGetLocation()) {
			gps.showSettingsAlert();
		}

		new GetContacts().execute();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		super.onResume();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.customer, menu);
		return super.onCreateOptionsMenu(menu);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_addcustomer:
			Intent intent = new Intent(this, AddCustomerActivity.class);
			startActivity(intent);
			finish();
			break;

		case R.id.menu_find_map:
			Intent intent1 = new Intent(this, CustomerOnMapActivity.class);
			startActivity(intent1);
			break;
		}
		return true;
	}

	/**
	 * Async task class to get json by making HTTP call
	 * */
	private class GetContacts extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(ListCustomerActivity.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@SuppressLint("DefaultLocale")
		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);

					// Getting JSON Array node
					customerJsonArray = jsonObj.getJSONArray(TAG_CUSTOMER);

					Log.e("Json Length", customerJsonArray.length() + "");
					// looping through All Contacts
					for (int i = 0; i < customerJsonArray.length(); i++) {
						JSONObject c = customerJsonArray.getJSONObject(i);

						String id = c.getString(TAG_ID);
						String name = c.getString(TAG_NAME);
						String employee = c.getString(TAG_EMPLOYEE);
						String address = c.getString(TAG_ADDRESS);
						String email = c.getString(TAG_EMAIL);
						String latitude = c.getString(TAG_LATITUDE);
						String longtitude = c.getString(TAG_LONGTITUDE);
						String phone_number = c.getString(TAG_PHONE_NUMBER);

						Customer customer = new Customer(Integer.parseInt(id),
								employee, name, address,
								Double.parseDouble(latitude),
								Double.parseDouble(longtitude), phone_number,
								email);

						double lati = gps.getLatitude();
						double longti = gps.getLongitude();

						Location locationA = new Location("Point A");
						locationA.setLatitude(lati);
						locationA.setLongitude(longti);

						Location locationB = new Location("Point B");
						locationB.setLatitude(Double.parseDouble(latitude));
						locationB.setLongitude(Double.parseDouble(longtitude));
						double distance = round(
								locationA.distanceTo(locationB) / 1000, 2);
						customer.setDistace(distance);

						// Phone node is JSON Object

						// adding contact to contact list
						dataArrayList.add(customer);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}
			Log.e("Add custom: ", "" + dataArrayList.size());
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into ListView
			 * */
			ListCustomerAdapter adapter = new ListCustomerAdapter(
					ListCustomerActivity.this, 1, dataArrayList);

			ListView listCustomer = (ListView) findViewById(R.id.list_customer);
			listCustomer.setAdapter(adapter);
			Log.e("Data length", "" + dataArrayList.size());

		}

	}

	public static double round(double value, int places) {
		if (places < 0)
			throw new IllegalArgumentException();

		long factor = (long) Math.pow(10, places);
		value = value * factor;
		long tmp = Math.round(value);
		return (double) tmp / factor;
	}
}
